class SessionMgr {
	//会话类，用于管理已连接的用户
	constructor() {
		this.sessions = {} //保存socket.id对应的session
		this.sessionsUid = {}; //保存uid对应的session
	}

	create(socket) {
		var session = new Session(socket);
		this.sessions[session.sId] = session;
		socket.on('close', function() {
			delSession(session)
		})
		return session;
	}

	get(sId) {
		return this.sessions[sId];
	}

	getByUid(uId) {
		return this.sessionsUid[uId];
	}

	bind(sId, uId) {
		if (this.sessionsUid[uId]) {
			//不允许同一账号登陆多个客户端
			//服务器先断开原来的客户端
			this.sessionsUid[uId].socket.disconnect();
		}
		var session = this.sessions[sId];
		session.uId = uId;
		this.sessionsUid[uId] = session;
		return session;
	}

	delSession(session) {
		delete this.sessions[this.sId];
		if (session.uId) {
			delete this.sessionsUid[session.uId];
		}
	}

}

class Session {
	constructor(socket) {
		this.sId = socket.id;
		this.uId = null; //登陆的用户id
		this.rId = null; //登陆的角色id
		this.socket = socket;
		this.setting = {};
	}
}

module.exports = new SessionMgr();
